package com.sf.wisdomkg.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sf.wisdomkg.R;
import com.sf.wisdomkg.utils.CommonUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.videolan.libvlc.EventHandler;
import org.videolan.libvlc.IVideoPlayer;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.LibVlcException;
import org.videolan.vlc.util.VLCInstance;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

/**
 * Created by ming on 2017/9/21.
 */
public class BabyOnlineDescActivity extends AppCompatActivity implements View.OnClickListener,SurfaceHolder.Callback, IVideoPlayer {

    private static final String SHARE_CONTENT = "app_";
    private SharedPreferences setting;

    private Button back_btn;
    private TextView bar_content,jianhu_tv,desc_name,desc_sex,desc_age,desc_address;
    private ImageView head_img;


    private String baseUrl = null;

    private String id,name;

    //视频播放
    private SurfaceView mSurfaceView;
    private LibVLC mMediaPlayer;
    private SurfaceHolder mSurfaceHolder;

    private View mLoadingView;

    private int mVideoHeight;
    private int mVideoWidth;
    private int mVideoVisibleHeight;
    private int mVideoVisibleWidth;
    private int mSarNum;
    private int mSarDen;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_babyonline_desc);

        Bundle bundle = this.getIntent().getExtras();
        id = bundle.getString("id");
        name = bundle.getString("name");
        getSupportActionBar().hide();
        initView();
        GetBabyLineDesc();
        GetBabyLineVideo();
        desc_name.setText(bundle.getString("name"));
        bar_content.setText(bundle.getString("name"));
        if (bundle.getString("sex").equals("0")){
            head_img.setImageResource(R.mipmap.boy_head_icon);

        }else {
            head_img.setImageResource(R.mipmap.girl_head_icon);
        }
        back_btn.setOnClickListener(this);
        jianhu_tv.setOnClickListener(this);

        mSurfaceView = (SurfaceView) findViewById(R.id.video);
        mLoadingView = findViewById(R.id.video_loading);
        try {
            mMediaPlayer = VLCInstance.getLibVlcInstance();
        } catch (LibVlcException e) {
            e.printStackTrace();
        }

        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setFormat(PixelFormat.RGBX_8888);
        mSurfaceHolder.addCallback(this);

        mMediaPlayer.eventVideoPlayerActivityCreated(true);

        EventHandler em = EventHandler.getInstance();
        em.addHandler(mVlcHandler);

        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mSurfaceView.setKeepScreenOn(true);
        //		mMediaPlayer.setMediaList();
        //		mMediaPlayer.getMediaList().add(new Media(mMediaPlayer, "http://live.3gv.ifeng.com/zixun.m3u8"), false);
        //		mMediaPlayer.playIndex(0);

//		mMediaPlayer.playMRL("rtsp://admin:admin@192.168.1.222:554/cam/realmonitor?channel=1&subtype=0");

    }

    /**
     * ui初始化
     */
    private void initView(){
        setting = this.getSharedPreferences(SHARE_CONTENT,0);
        if (setting.getString("roleId","").equals("2")){
            baseUrl = CommonUtils.IP_S + CommonUtils.M_T;
        }else if (setting.getString("roleId","").equals("3")){
            baseUrl = CommonUtils.IP_S + CommonUtils.M_S;
        }else if (setting.getString("roleId","").equals("1")){
            baseUrl = CommonUtils.IP_S + CommonUtils.M_T;
        }


        back_btn = (Button)findViewById(R.id.back_btn);
        bar_content = (TextView)findViewById(R.id.bar_content);
        jianhu_tv = (TextView)findViewById(R.id.jianhu_tv);
        desc_name = (TextView)findViewById(R.id.desc_name);
        desc_sex = (TextView)findViewById(R.id.desc_sex);
        desc_age = (TextView)findViewById(R.id.desc_age);
        desc_address = (TextView)findViewById(R.id.desc_address);
        head_img = (ImageView)findViewById(R.id.head_img);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back_btn:
                finish();
                break;
            case R.id.jianhu_tv:

//                if (setting.getString("roleId","").equals("3")){
//                    CommonUtils.confirm_info(BabyOnlineDescActivity.this,"暂未开放");
//                }else{
                    Intent intent = new Intent(BabyOnlineDescActivity.this,JianHuRenListActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("id",id);
                    bundle.putString("name",name);
                    intent.putExtras(bundle);
                    startActivity(intent);

//                }

                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mSurfaceView.setKeepScreenOn(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null) {
            mMediaPlayer.eventVideoPlayerActivityCreated(false);

            EventHandler em = EventHandler.getInstance();
            em.removeHandler(mVlcHandler);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        setSurfaceSize(mVideoWidth, mVideoHeight, mVideoVisibleWidth, mVideoVisibleHeight, mSarNum, mSarDen);
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (mMediaPlayer != null) {
            mSurfaceHolder = holder;
            mMediaPlayer.attachSurface(holder.getSurface(), this);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mSurfaceHolder = holder;
        if (mMediaPlayer != null) {
            mMediaPlayer.attachSurface(holder.getSurface(), this);//, width, height
        }
        if (width > 0) {
            mVideoHeight = height;
            mVideoWidth = width;
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mMediaPlayer != null) {
            mMediaPlayer.detachSurface();
        }
    }

    @Override
    public void setSurfaceSize(int width, int height, int visible_width, int visible_height, int sar_num, int sar_den) {
        mVideoHeight = height;
        mVideoWidth = width;
        mVideoVisibleHeight = visible_height;
        mVideoVisibleWidth = visible_width;
        mSarNum = sar_num;
        mSarDen = sar_den;
        mHandler.removeMessages(HANDLER_SURFACE_SIZE);
        mHandler.sendEmptyMessage(HANDLER_SURFACE_SIZE);
    }

    private static final int HANDLER_BUFFER_START = 1;
    private static final int HANDLER_BUFFER_END = 2;
    private static final int HANDLER_SURFACE_SIZE = 3;

    private static final int SURFACE_BEST_FIT = 0;
    private static final int SURFACE_FIT_HORIZONTAL = 1;
    private static final int SURFACE_FIT_VERTICAL = 2;
    private static final int SURFACE_FILL = 3;
    private static final int SURFACE_16_9 = 4;
    private static final int SURFACE_4_3 = 5;
    private static final int SURFACE_ORIGINAL = 6;
    private int mCurrentSize = SURFACE_BEST_FIT;

    private Handler mVlcHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg == null || msg.getData() == null)
                return;

            switch (msg.getData().getInt("event")) {
                case EventHandler.MediaPlayerTimeChanged:
                    break;
                case EventHandler.MediaPlayerPositionChanged:
                    break;
                case EventHandler.MediaPlayerPlaying:
                    mHandler.removeMessages(HANDLER_BUFFER_END);
                    mHandler.sendEmptyMessage(HANDLER_BUFFER_END);
                    break;
                case EventHandler.MediaPlayerBuffering:
                    break;
                case EventHandler.MediaPlayerLengthChanged:
                    break;
                case EventHandler.MediaPlayerEndReached:
                    //播放完成
                    break;
            }

        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_BUFFER_START:
                    showLoading();
                    break;
                case HANDLER_BUFFER_END:
                    hideLoading();
                    break;
                case HANDLER_SURFACE_SIZE:
                    changeSurfaceSize();
                    break;
            }
        }
    };

    private void showLoading() {
        mLoadingView.setVisibility(View.VISIBLE);
    }

    private void hideLoading() {
        mLoadingView.setVisibility(View.GONE);
    }

    private void changeSurfaceSize() {
        // get screen size
        int dw = getWindowManager().getDefaultDisplay().getWidth();
        int dh = getWindowManager().getDefaultDisplay().getHeight();

        // calculate aspect ratio
        double ar = (double) mVideoWidth / (double) mVideoHeight;
        // calculate display aspect ratio
        double dar = (double) dw / (double) dh;

        switch (mCurrentSize) {
            case SURFACE_BEST_FIT:
                if (dar < ar)
                    dh = (int) (dw / ar);
                else
                    dw = (int) (dh * ar);
                break;
            case SURFACE_FIT_HORIZONTAL:
                dh = (int) (dw / ar);
                break;
            case SURFACE_FIT_VERTICAL:
                dw = (int) (dh * ar);
                break;
            case SURFACE_FILL:
                break;
            case SURFACE_16_9:
                ar = 16.0 / 9.0;
                if (dar < ar)
                    dh = (int) (dw / ar);
                else
                    dw = (int) (dh * ar);
                break;
            case SURFACE_4_3:
                ar = 4.0 / 3.0;
                if (dar < ar)
                    dh = (int) (dw / ar);
                else
                    dw = (int) (dh * ar);
                break;
            case SURFACE_ORIGINAL:
                dh = mVideoHeight;
                dw = mVideoWidth;
                break;
        }

        mSurfaceHolder.setFixedSize(mVideoWidth, mVideoHeight);
        ViewGroup.LayoutParams lp = mSurfaceView.getLayoutParams();
        lp.width = dw;
        lp.height = dh;
        mSurfaceView.setLayoutParams(lp);
        mSurfaceView.invalidate();
    }


    /**
     * 在线数据
     */
    private void GetBabyLineDesc() {
        RequestParams params = new RequestParams(baseUrl + "student/studentdetail");


        if (setting.getString("roleId","").equals("2")){
            params.addParameter("studentId",id);
        }else if (setting.getString("roleId","").equals("3")){
            params.addParameter("studentId",id);
        }else if (setting.getString("roleId","").equals("1")){
            params.addParameter("studentId",id);
        }

        //联网设置
        params.setCacheMaxAge(1000*60);
        System.out.println("请求"+params);
        params.setConnectTimeout(90000);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("请求"+result);
                //解析result
                if (result != null){
                    try {
                        JSONObject jsonObject  = new JSONObject(result);
                        if (jsonObject.optString("status").equals("true")){
                            JSONObject jsonObj = jsonObject.getJSONObject("data");
                            jianhu_tv.setText("Ta的监护人("+jsonObj.optString("amount")+")>>");
                            if (jsonObj.optString("sex").equals("0")){
                                desc_sex.setText("男");
                            }else {
                                desc_sex.setText("女");
                            }
                            desc_age.setText(jsonObj.optString("age"));
                            desc_address.setText(jsonObj.optString("address"));
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                System.out.println("请求"+ex);
                Toast.makeText(BabyOnlineDescActivity.this, "连接服务器失败,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(BabyOnlineDescActivity.this, "请求超时,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 在线数据
     */
    private void GetBabyLineVideo() {
        RequestParams params = new RequestParams(baseUrl + "device/getDevice");
        params.addParameter("returnId",setting.getString("returnId",""));
        //联网设置
        params.setCacheMaxAge(1000*60);
        System.out.println("请求"+params);
        params.setConnectTimeout(90000);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("请求"+result);
                //解析result
                if (result != null){
                    try {
                        JSONObject jsonObject  = new JSONObject(result);
                        if (jsonObject.optString("status").equals("true")){
                            JSONObject jsonObj = jsonObject.getJSONObject("data");
                            String username = jsonObj.optString("username");
                            String password = jsonObj.optString("password");
                            String ip = jsonObj.optString("ip");
                            String port = jsonObj.optString("port");
                            String number = jsonObj.optString("number");
                            System.out.println("拼接的值"+"rtsp://"+username+":"+password+"@"+ip+":"+port+"/Streaming/Channels/"+number+"");
                            mMediaPlayer.playMRL("rtsp://"+username+":"+password+"@"+ip+":"+port+"/Streaming/Channels/"+number+"");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                System.out.println("请求"+ex);
                Toast.makeText(BabyOnlineDescActivity.this, "连接服务器失败,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(BabyOnlineDescActivity.this, "请求超时,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }
}
